﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;  

public partial class InsertScores : System.Web.UI.Page
{
    public string URL_SERVICE = "http://192.168.1.26/ptss/ptss.asmx";

    public const string TXT_ERROR_CONNECTION = "Check connection";
    public const string TXT_ERROR_CAPTION_MESSAGE = "Error";
    public const string TXT_ERROR = "Error";
    public const string TXT_CONNECTION_ERROR = "Check connection";
    public const string TXT_DELETE_SCORE_QUESTION = "Delete score?";
    public const string TXT_DELETE_SCORE = "Delete score";
    public const string TXT_CONFIRM_CAPTION_MESSAGE = "Confirm";
    public const string TXT_RESULT_CAPTION_MESSAGE = "Result";
    public const string TXT_JOKER_TIME = "Joker time";
    public const string TXT_SEND_SCORE = "Send score";
    public const string TXT_DELETE_OK = "Delete succesfully...";
    public const string TXT_NEW_SCORE = "New Score: ";
    public const string TXT_SAVE_ERROR = "Save error..";
    public const string TXT_SAVE_OK = "Save succesfully..";

    public const string FIELD_PLAYER_NICK_NUMBER = "PlayerNickNumber";
    public const string FIELD_PK_MACHINE = "Pk_Machine";
    public const string FIELD_PK_PLAYER = "Pk_Player";
    public const string FIELD_MACHINE_ACRON_NUMBER = "Machine_AcronNumber";
    public const string FIELD_TOURNAMENT_NAME = "Tournament_Name";
    public const string FIELD_PK_TOURNAMENT = "Pk_Tournament";

    

    public ptss oService = new ptss();
    public Boolean HavePreviousScore = false;
   
    private void ResetValues(bool IncludeTour){

        txt_Score.Text = string.Empty;
        txt_Score.Enabled = true;
        btn_send.Disabled = false;
        cmbMachine.Enabled = true;
        cmbPlayer.Enabled = true;
        cmb_QTour.Enabled = true;

        lbl_server.Text = URL_SERVICE;

        if (IncludeTour)
        {
            Session["oTour"] = oService.GetTournaments();

            cmb_QTour.DataTextField = FIELD_TOURNAMENT_NAME;
            cmb_QTour.DataValueField = FIELD_PK_TOURNAMENT;

            cmb_QTour.DataSource = (List<Tournament>)Session["oTour"];
            cmb_QTour.DataBind();

            bool IsInQualify = oService.GetIfTournamentsIsInQualify(Convert.ToInt32(cmb_QTour.SelectedValue.ToString()));
            Qualify.Enabled = true;
            Playoffs.Enabled = true;
            if (IsInQualify)
            {
                Qualify.Checked = true;
                Playoffs.Checked = false;
            }
            else
            {
                Qualify.Checked = false;
                Playoffs.Checked = true;
            }
            Qualify.Enabled = false;
            Playoffs.Enabled = false;
        }
        if (((List<Tournament>)Session["oTour"]).Count > 0)
        {

            Session["oPlayers"] = oService.GetPlayers(Convert.ToInt32(cmb_QTour.SelectedValue.ToString()), Qualify.Checked);

            cmbPlayer.DataTextField = FIELD_PLAYER_NICK_NUMBER;
            cmbPlayer.DataValueField = FIELD_PK_PLAYER;
            cmbPlayer.DataSource = (List<Player>)Session["oPlayers"];
            cmbPlayer.DataBind();
        }
        else {            
            cmbMachine.Enabled = false;
            cmbPlayer.Enabled = false;
            cmb_QTour.Enabled = false; 
            return;
        }
        Session["oMachines"] = oService.GetMachinesByPlayerAutoDetectRound(Convert.ToInt32(cmb_QTour.SelectedValue.ToString()), Convert.ToInt32(cmbPlayer.SelectedValue.ToString()));

        if (((List<Machine>)Session["oMachines"]).Count > 0)
        {                 
            cmbMachine.DataTextField = FIELD_MACHINE_ACRON_NUMBER;
            cmbMachine.DataValueField = FIELD_PK_MACHINE;
            cmbMachine.DataSource = (List<Machine>)Session["oMachines"];
            cmbMachine.DataBind();
        }
        else
        {
            cmbMachine.Enabled = false;           
        }

        long Score = oService.GetPlayerScore(Convert.ToInt32(cmb_QTour.SelectedValue.ToString()), Convert.ToInt32(cmbPlayer.SelectedValue.ToString()), Convert.ToInt32(cmbMachine.SelectedValue.ToString()), Qualify.Checked);
       
        if (Score > -1)
        {
            txt_Score.Text = Score.ToString();

            if (Qualify.Checked)
            {
                bool HavePreviousJoker = QualifyRounds.HavePreviousJokerScore(Convert.ToInt32(cmb_QTour.SelectedValue.ToString()), Convert.ToInt32(cmbPlayer.SelectedValue.ToString()));
                if (HavePreviousJoker)
                {
                    btn_send.Value = "SCORE/JOKER INSERTED";
                    btn_send.Disabled = true;
                    txt_Score.Enabled = false;
                }
                else
                {

                    btn_send.Value = "SEND JOKER SCORE";
                    IsJoker.Checked = true;
                }
            }
            else
            {

                btn_send.Value = "SCORE INSERTED";
                IsJoker.Checked = true;
                btn_send.Disabled = true;
                txt_Score.Enabled = false;
            }
        }
        else
        {
            IsJoker.Checked = false;
        }      
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            URL_SERVICE = (string)Application["UrlService"];
            btn_send.Disabled = false;
            AjaxPro.Utility.RegisterTypeForAjax(typeof(InsertScores));

            if (!Page.IsPostBack)
            {
               
                ResetValues(true);  
            }  
        }
        catch (NullReferenceException Null)
        {
            Response.Write("<script language='javascript'>alert('" +
            Server.HtmlEncode(Null.Message) + "')</script>");

        }
        catch (Exception Ex)
        {
            Response.Write("<script language='javascript'>alert('" +
           Server.HtmlEncode(Ex.Message) + "')</script>");
        } 
        
    }

   

    private int GetMachineNumberByPk(int pk)
    {
        int res = -1;
        try
        {

            if (Session["oMachines"]!= null)
            {
                foreach (Machine iMachine in (List<Machine>)Session["oMachines"])
                {
                    if (pk == iMachine.Pk_Machine)
                    {
                        res = iMachine.Machine_Number;
                    }
                }
            }
            return res;
        }
        catch (NullReferenceException Null)
        {
            Response.Write("<script language='javascript'>alert('" +
            Server.HtmlEncode(Null.Message) + "')</script>");
            return res;
        }
        catch (Exception Ex)
        {
            Response.Write("<script language='javascript'>alert('" +
           Server.HtmlEncode(Ex.Message) + "')</script>");
            return res;
        }
    }

    private int GetMachinePkByNumber(int number)
    {
        int res = -1;
        try
        {

            if (Session["oMachines"] != null)
            {
                foreach (Machine iMachine in (List<Machine>)Session["oMachines"])
                {
                    if (number == iMachine.Machine_Number)
                    {
                        res = iMachine.Pk_Machine;
                    }
                }
            }
            return res;
        }
        catch (NullReferenceException Null)
        {
            Response.Write("<script language='javascript'>alert('" +
            Server.HtmlEncode(Null.Message) + "')</script>");
            return res;
        }
        catch (Exception Ex)
        {
            Response.Write("<script language='javascript'>alert('" +
           Server.HtmlEncode(Ex.Message) + "')</script>");
            return res;
        }
    }
    private int GetPlayerNumberByPk(int pk){
        int res = -1;
        try
        {

            if (Session["oPlayers"] != null)
            {
                foreach (Player iPLayer in (List<Player>)Session["oPlayers"])
                {
                    if (pk == iPLayer.Pk_Player) {
                        res = iPLayer.Player_Number;
                    } 
                }
            }
            return res;
        }
        catch (NullReferenceException Null)
        {
            Response.Write("<script language='javascript'>alert('" +
            Server.HtmlEncode(Null.Message) + "')</script>");
            return res;
        }
        catch (Exception Ex)
        {
            Response.Write("<script language='javascript'>alert('" +
           Server.HtmlEncode(Ex.Message) + "')</script>");
            return res;
        } 
    }

    private int GetPkPlayerByNumber(int number)
    {
        int res = -1;
        try
        {

            if (Session["oPlayers"] != null)
            {
                foreach (Player iPLayer in (List<Player>)Session["oPlayers"])
                {
                    if (number == iPLayer.Player_Number)
                    {
                        res = iPLayer.Pk_Player;
                    }
                }
            }
            return res;
        }
        catch (NullReferenceException Null)
        {
            Response.Write("<script language='javascript'>alert('" +
            Server.HtmlEncode(Null.Message) + "')</script>");
            return res;
        }
        catch (Exception Ex)
        {
            Response.Write("<script language='javascript'>alert('" +
           Server.HtmlEncode(Ex.Message) + "')</script>");
            return res;
        }
    }
    protected void cmb_QTour_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            btn_send.Disabled = false;
            bool IsInQualify = oService.GetIfTournamentsIsInQualify(Convert.ToInt32(cmb_QTour.SelectedValue.ToString()));
            Qualify.Enabled = true;
            Playoffs.Enabled = true;
            if (IsInQualify)
            {
                Qualify.Checked = true;
                Playoffs.Checked = false;
            }
            else
            {
                Qualify.Checked = false;
                Playoffs.Checked = true;
            }
            Qualify.Enabled = false;
            Playoffs.Enabled = false;

            
            Session["oPlayers"] = oService.GetPlayers(Convert.ToInt32(cmb_QTour.SelectedValue.ToString()), Qualify.Checked);

            if (Session["oPlayers"] != null)
            {
                if (((List<Player>)Session["oPlayers"]).Count > 0)
                {
                    cmbPlayer.Enabled = true;
                    cmbMachine.Enabled = true;
                    cmbPlayer.DataTextField = FIELD_PLAYER_NICK_NUMBER;
                    cmbPlayer.DataValueField = FIELD_PK_PLAYER;
                    cmbPlayer.DataSource = (List<Player>)Session["oPlayers"];
                    cmbPlayer.DataBind();

                    //MACHINES:
                    RefreshPlayers();

                   /////
                }
                else
                {
                    cmbPlayer.Enabled = false;
                    cmbMachine.Enabled = false;
                }
            }
            else {
                cmbPlayer.Enabled = false;
                cmbMachine.Enabled = false;
            }
           
        }
        catch (NullReferenceException Null)
        {
            Response.Write("<script language='javascript'>alert('" +
            Server.HtmlEncode(Null.Message) + "')</script>");

        }
        catch (Exception Ex)
        {
            Response.Write("<script language='javascript'>alert('" +
           Server.HtmlEncode(Ex.Message) + "')</script>");
        } 
    }
    private void RefreshPlayers() {
        try
        {
          
            Session["oMachines"] = oService.GetMachinesByPlayerAutoDetectRound(Convert.ToInt32(cmb_QTour.SelectedValue.ToString()), Convert.ToInt32(cmbPlayer.SelectedValue.ToString()));

            if (((List<Machine>)Session["oMachines"]).Count > 0)
            {
                cmbMachine.Enabled = true;
                cmbMachine.DataTextField = FIELD_MACHINE_ACRON_NUMBER;
                cmbMachine.DataValueField = FIELD_PK_MACHINE;
                cmbMachine.DataSource = (List<Machine>)Session["oMachines"];
                cmbMachine.DataBind();
            }
            else
            {
                cmbMachine.Enabled = false;
            }

            RefreshMachines();


        }
        catch (NullReferenceException Null)
        {
            Response.Write("<script language='javascript'>alert('" +
            Server.HtmlEncode(Null.Message) + "')</script>");

        }
        catch (Exception Ex)
        {
            Response.Write("<script language='javascript'>alert('" +
           Server.HtmlEncode(Ex.Message) + "')</script>");
        } 
    }
    protected void cmbPlayer_SelectedIndexChanged(object sender, EventArgs e)
    {
        btn_send.Disabled = false;
        RefreshPlayers(); 
    }

    private void RefreshMachines(){
        try
        {
             btn_send.Disabled = false;
             txt_Score.Enabled = true;
            bool havejoker = false;
            bool IsInQualify = oService.GetIfTournamentsIsInQualify(Convert.ToInt32(cmb_QTour.SelectedValue.ToString()));
            Qualify.Enabled = true;
            Playoffs.Enabled = true;
            if (IsInQualify)
            {
                Qualify.Checked = true;
                Playoffs.Checked = false;
            }
            else
            {
                Qualify.Checked = false;
                Playoffs.Checked = true;
            }

            if (Qualify.Checked)
            {
                havejoker = QualifyRounds.HavePreviousJokerScore(Convert.ToInt32(cmb_QTour.SelectedValue.ToString()), Convert.ToInt32(cmbPlayer.SelectedValue.ToString()));
                
            }

            long Score = oService.GetPlayerScore(Convert.ToInt32(cmb_QTour.SelectedValue.ToString()), Convert.ToInt32(cmbPlayer.SelectedValue.ToString()), Convert.ToInt32(cmbMachine.SelectedValue.ToString()), Qualify.Checked);
            txt_Score.Text = Score.ToString();
            if (Score > -1)
            {
                if (Qualify.Checked)
                {
                    if (havejoker)
                    {
                        btn_send.Disabled = true;
                        txt_Score.Enabled = false;
                        btn_send.Value = "SCORE/JOKER INSERTED";
                    }
                    else
                    {
                        txt_Score.Text = Score.ToString();
                        btn_send.Value = "SEND JOKER SCORE";
                        IsJoker.Checked = true;
                    }
                }
                else {
                    btn_send.Disabled = true;
                    txt_Score.Enabled = false;
                    btn_send.Value = "SCORE INSERTED";
                }
            }
            else
            {
                btn_send.Value = "SEND SCORE";
                txt_Score.Text = "";
                IsJoker.Checked = false;
            }

        }
        catch (NullReferenceException Null)
        {
            Response.Write("<script language='javascript'>alert('" +
            Server.HtmlEncode(Null.Message) + "')</script>");

        }
        catch (Exception Ex)
        {
            Response.Write("<script language='javascript'>alert('" +
           Server.HtmlEncode(Ex.Message) + "')</script>");
        }
    }
    protected void cmbMachine_SelectedIndexChanged(object sender, EventArgs e)
    {
        btn_send.Disabled = false;
       RefreshMachines();
    }


    private bool IsNumber(string Number) {
        try
        {

            string Str = Number.Trim();
            if (Str == string.Empty) return false;
            Int64 Num;
            return Int64.TryParse(Str, out Num);
          
        }
        catch {
            return false;
        } 
    
    }
   
    protected void IsJoker_CheckedChanged(object sender, EventArgs e)
    {

    }

    public void GetSend(object sender, EventArgs e)
    {
        if (txt_Score.Text == "-1")
        {
            ResponseMessage.Value = "Error HOLA";
        }
        else {
            ResponseMessage.Value = "Error HOLA";
        
        }
    }

    [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.Read)]
    public int InsertPlayerScore(string Score, int TournamentID, int PlayerID, int MachineID)
    {
        try
        {


            if (Score == "-1")
            {
                return -1;
            }
            else
            {
                if (IsNumber(Score))
                {
                    string error;
                    bool IsInQualify = oService.GetIfTournamentsIsInQualify(Convert.ToInt32(TournamentID));
                    bool IsJoker = false;
                    long HaveScore = oService.GetPlayerScore(Convert.ToInt32(TournamentID), Convert.ToInt32(PlayerID), Convert.ToInt32(MachineID), IsInQualify);
                    if (HaveScore > -1) {
                        IsJoker = true;
                    }
                    if (IsJoker == true && IsInQualify == true) {
                        bool havepreviousjoker = QualifyRounds.HavePreviousJokerScore(Convert.ToInt32(TournamentID), Convert.ToInt32(PlayerID));
                        if (havepreviousjoker == true)
                        {
                            //btn_send.Disabled = true;
                            //btn_send.Value = "SCORE/JOKER INSERTED";
                            return -1;
                        }
                    } 
        
                    bool res = oService.InsertPlayerScore(Convert.ToInt32(TournamentID),
                                                           Convert.ToInt32(PlayerID),
                                                           Convert.ToInt32(MachineID),
                                                           long.Parse(Score),
                                                           IsInQualify,
                                                           IsJoker,
                                                           out error);
                   
                  

                    if (res == true)
                    {
                       
                        return 0;
                    }
                    else
                    {
                        return -1;
                    }

                }
                else
                {
                    return -1;
                }
            }

        }
        catch (Exception Ex) {
            string error = Ex.ToString();
            return -1;
        }
    
    }

    //protected void btn_send_Click(object sender, EventArgs e)
    //{
    //    try
    //    {

            

    //        if (txt_Score.Text == "-1")
    //        {
    //            ResponseMessage.Value = "Error HOLA";
               

    //            //Response.Write("<script language='javascript'>OpenMessage('asas');</script>");
    //            //Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "script", "alert('Lechono!');", true);
    //            //Response.Write("<script language='javascript'>alert('NI DE COÑA!!! Si la has cagado da la cara en la mesa de control y te borramos la puntuación.')</script>");
    //            //Response.Write("<script language='javascript'>$( document ).delegate(\"#aboutPage\", \"pageinit\", function() { alert('A page with an id of \"aboutPage\" was just created by jQuery Mobile!</script>');});");
    //        }
    //        else
    //        {
    //            if (IsNumber(txt_Score.Text))
    //            {
    //                string error;
    //                bool res = oService.InsertPlayerScore(Convert.ToInt32(cmb_QTour.SelectedValue.ToString()),
    //                                                       Convert.ToInt32(cmbPlayer.SelectedValue.ToString()),
    //                                                       Convert.ToInt32(cmbMachine.SelectedValue.ToString()),
    //                                                       long.Parse(txt_Score.Text),
    //                                                       Qualify.Checked,
    //                                                       IsJoker.Checked,
    //                                                       out error);

    //                if (res == true)
    //                {
    //                    //Response.Write("<script language='javascript'>alert('ERES UN CRACK! TODO CORRECTO')</script>");
    //                    //txt_Score.Text = string.Empty; 
    //                }
    //                else
    //                {
    //                    //Response.Write("<script language='javascript'>alert('Jodido lechón algo has jodido, putos usuarios')</script>");

    //                }

    //            }
    //            else
    //            {
    //               // Response.Write("<script language='javascript'>alert('Jodido lechón mete los putos puntos!')</script>");
    //            }
    //        }
                             
    //    }
    //    catch (NullReferenceException Null)
    //    {
    //        Response.Write("<script language='javascript'>alert('" +
    //        Server.HtmlEncode(Null.Message) + "')</script>");

    //    }
    //    catch (Exception Ex)
    //    {
    //        Response.Write("<script language='javascript'>alert('" +
    //       Server.HtmlEncode(Ex.Message) + "')</script>");
    //    }


    //}

    private void UpdateScore() { 
    
    }
    
    protected void Qualify_CheckedChanged(object sender, EventArgs e)
    {
        ResetValues(false);
    }
    protected void Playoffs_CheckedChanged(object sender, EventArgs e)
    {
        ResetValues(false);
    }
    protected void Btn_Refresh_Click(object sender, EventArgs e)
    {
        ResetValues(true);
    }
   
    protected void btn_findplayer_Click(object sender, EventArgs e)
    {
        try
        {
            //if (IsNumber(txtPlayer.Text))
            //{
            //    int PlayerPk = GetPkPlayerByNumber(int.Parse(txtPlayer.Text.Trim()));
            //    if (cmbPlayer.Items.FindByValue(PlayerPk.ToString()) != null) // or IndVal.ToString() 
            //    {
            //        cmbPlayer.SelectedValue = PlayerPk.ToString();
            //        RefreshMachines();
            //    }
            //    else {
            //        Response.Write("<script language='javascript'>alert('Usuario no encontrado')</script>");
            //        UpdatePlayerNumberText();
            //    }
                
            //}
            //else
            //{
            //    Response.Write("<script language='javascript'>alert('Mete un numero capullo')</script>");
            //    UpdatePlayerNumberText();
            //}
        }
        catch (NullReferenceException Null)
        {
            Response.Write("<script language='javascript'>alert('" +
            Server.HtmlEncode(Null.Message) + "')</script>");

        }
        catch (Exception Ex)
        {
            Response.Write("<script language='javascript'>alert('" +
           Server.HtmlEncode(Ex.Message) + "')</script>");
        }
    }
    protected void btn_findmachine_Click(object sender, EventArgs e)
    {
        try
        {
            //if (IsNumber(txtMachine.Text))
            //{
            //    int MachinePk = GetMachinePkByNumber(int.Parse(txtMachine.Text.Trim()));
            //    if (cmbMachine.Items.FindByValue(MachinePk.ToString()) != null) // or IndVal.ToString() 
            //    {
            //        cmbMachine.SelectedValue = MachinePk.ToString();
            //        RefreshMachines();
            //    }
            //    else {
                    
            //        Response.Write("<script language='javascript'>alert('Usuario no encontrado')</script>");
            //        UpdateMachineNumberText(); 
            //    }

            //}
            //else
            //{
            //    Response.Write("<script language='javascript'>alert('Mete un numero capullo')</script>");
               
                
            //}
        }
        catch (NullReferenceException Null)
        {
            Response.Write("<script language='javascript'>alert('" +
            Server.HtmlEncode(Null.Message) + "')</script>");

        }
        catch (Exception Ex)
        {
            Response.Write("<script language='javascript'>alert('" +
           Server.HtmlEncode(Ex.Message) + "')</script>");
        }
    }
}
